package com.central.scheduler.plugin.task.datax.json.reader;

import cn.hutool.json.JSONObject;
import com.central.common.entity.ReaderParams;
import com.central.common.model.DatasourceInfo;
import com.central.scheduler.plugin.task.datax.json.ReaderJson;
import com.central.scheduler.spi.utils.JSONUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @author Tindy
 * @date 2022/3/10
 * @describe
 */
@Getter
@Setter
public class HiveReaderJson implements ReaderJson {
    private List<String> column=new ArrayList<>();
    private String jdbcUrl;
    private String kerberosConfFilePath;
    private String kerberosKeytabFilePath;
    private String kerberosPrincipal;
    private boolean haveKerberos;
    private String username;
    private String password;
    private String table;
    private String where;

    public HiveReaderJson(ReaderParams reader, DatasourceInfo readerDatasource) {
        this.column = reader.getColumn();
        this.jdbcUrl="jdbc:hive2://"+readerDatasource.getHost()+ ":" + readerDatasource.getPort() + "/"+reader.getDbName();
        String other = buildOther(readerDatasource.getOther(), ";");
        if (StringUtils.isNotEmpty(other)) {
            this.jdbcUrl += ";" + other;
        }
        this.where=reader.getWhere();
        this.username=readerDatasource.getUsername();
        this.password=readerDatasource.getPassword();
        this.table=reader.getTbName();
        this.kerberosPrincipal=readerDatasource.getUsername();

    }
    /**
     * 生成其他参数
     * @return
     */
    public String buildOther(String other,String separator){
        StringBuilder otherSb = new StringBuilder();
        if (! StringUtils.isBlank(other)) {
            Map map = JSONUtils.parseObject(other, new TypeReference<LinkedHashMap<String, String>>() {
            });
            if (map.size() > 0) {
                Set<String> keys = map.keySet();
                for (String key : keys) {
                    otherSb.append(String.format("%s=%s%s", key, map.get(key), separator));
                }
                otherSb.deleteCharAt(otherSb.length() - 1);
            }
        }
        return otherSb.toString();
    }
}
